package cn.sh.cares.mule.services.transformer;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractTransformer;

public class HelloWorldHttpTransformer extends AbstractTransformer {

	private static final String NAME_REQUEST_PARAMETER = "name=";
	private static final String REQUEST_PARAMETER = "name";
	
	protected Object doTransform(Object src, String encoding)
			throws TransformerException {
		
		String request = src.toString();
		
        String requestQuery = null;
        
        if (request != null && request.length() > 0 && request.indexOf('?') != -1)
        {
            requestQuery = request.substring(request.indexOf('?') + 1).trim();
        }

        return extractNameValue(requestQuery);
	}

    private String extractNameValue(String requestQuery) throws TransformerException
    {
        String nameValue = null;
        
        if (requestQuery != null && requestQuery.length() > 0)
        {
            int nameParameterPos = requestQuery.indexOf(NAME_REQUEST_PARAMETER);
            if (nameParameterPos != -1)
            {
                int nextParameterValuePos = requestQuery.indexOf('&'); 
                if (nextParameterValuePos == -1 || nextParameterValuePos < nameParameterPos)
                {
                    nextParameterValuePos = requestQuery.length();
                }

                nameValue = requestQuery.substring(nameParameterPos + NAME_REQUEST_PARAMETER.length(), nextParameterValuePos);
            }
            
            if (nameValue != null && nameValue.length() > 0)
            {
                try
                {
                    nameValue = URLDecoder.decode(nameValue, "UTF-8");
                }
                catch (UnsupportedEncodingException uee)
                {
                    uee.printStackTrace();
                }
            }
        }

        if (nameValue == null)
        {
            nameValue = "";
        }
        
        return nameValue;
    }	
}
